package br.com.future.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.log4j.Logger;

import br.com.future.dao.interfaces.EnderecoDAOI;
import br.com.future.jdbc.ConnectionFactory;
import br.com.future.log4j.Log4j;
import br.com.future.model.Bairro;
import br.com.future.model.Endereco;
import br.com.future.model.TipoLogradouro;

public class EnderecoDAO implements EnderecoDAOI {
	
	//chamando o metodo da classe Log4j.
	static Logger logger = Logger.getLogger(Log4j.class);

	private Connection conn = null;
	private boolean flag = true;

	public EnderecoDAO(Connection conn) {
		this.conn = conn;
	}

	public EnderecoDAO() {

	}

	public Endereco consultar(int idEndereco) {

		verificarInstanciaDeConnection();

		String sql = "SELECT CD_ENDERECO, CD_TIPO_LOGRADOURO, CD_BAIRRO, NM_LOGRADOURO, NR_CEP FROM AM_ENDERECO WHERE CD_ENDERECO = ?";

		PreparedStatement ps = null;

		ResultSet rs = null;

		Endereco endereco = new Endereco();

		try {

			ps = conn.prepareStatement(sql);
			ps.setInt(1, idEndereco);
			rs = ps.executeQuery();

			if (rs.next()) {
				endereco.setCodigoEndereco(rs.getInt("CD_ENDERECO"));
				TipoLogradouro tipoLogradouro = new TipoLogradouroDAO(conn)
						.consultar(rs.getInt("CD_TIPO_LOGRADOURO"));
				endereco.setTipoLogradouro(tipoLogradouro);
				Bairro bairro = new BairroDAO(conn).consultar(rs
						.getInt("CD_BAIRRO"));
				endereco.setBairro(bairro);
				endereco.setNomeLogradouro(rs.getString("NM_LOGRADOURO"));
				endereco.setCep(rs.getInt("NR_CEP"));

			}

		} catch (SQLException e) {
			e.printStackTrace();
			//chamando a mensagem.
			logger.error(e.getMessage());
		} finally {
			if(flag){
				ConnectionFactory.closeConnectionOracle(conn, rs, ps);
			}
		}
		return endereco;
	}
	
	private void verificarInstanciaDeConnection() {
		flag = true;
		
		if(conn == null){
			conn = ConnectionFactory.getConnection();
		}else{
			flag = false;
		}
	}

}
